from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
# from django.core.cache import cache
# import requests
# import logging

# from django.conf import settings
from tsl_backend.fgr_api.views import fgr_apis as fgr_apis

# For frontend usage: username and password will be sent to FGR for authentication
def get_tokens_for_ewo_user(username: str, password: str):
    # Send username and password to FGR for authentication
    # user = authenticate(username=username, password=password)
    message, user=fgr_apis.eorderAuth(username, password)

    if user is not None:
        refresh = RefreshToken.for_user(user)
        refresh["username"] = user.get_username()
        return message, {
            "username": str(user.get_username()),
            "refresh_token": str(refresh),
            "access_token": str(refresh.access_token),
        }
    else:
        return message, None

# For FGR usage: username and password of fgr user will be authenticated with this api
def get_tokens_for_fgr(username: str, password: str):
    # Send username and password to FGR for authentication
    user = authenticate(username=username, password=password)

    if user is not None:
        refresh = RefreshToken.for_user(user)
        refresh["username"] = user.get_username()
        return {
            "username": str(user.get_username()),
            "refresh_token": str(refresh),
            "access_token": str(refresh.access_token),
        }
    else:
        return None

def blacklist_token(refresh_token):
    token = RefreshToken(refresh_token)
    token.blacklist()